package com.flykoc.lightinggem.listener;

import com.flykoc.lightinggem.api.GemAPI;
import org.apache.commons.lang.math.RandomUtils;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.inventory.ItemStack;

/**
 * 伤害实体监听
 *
 * @author Zoyn
 * @since 2017-10-22
 */
public class EntityDamageByEntityListener implements Listener {

    @EventHandler
    public void onDamage(EntityDamageByEntityEvent e) {
        Entity damager = e.getDamager();
        Entity entity = e.getEntity();
        if (!(damager instanceof Player)) {
            return;
        }
        if (entity == null) {
            return;
        }
        Player player = (Player) damager;
        ItemStack itemStack = GemAPI.getItemInMainHand(player);
        if (itemStack == null) {
            return;
        }
        if (!GemAPI.hasLore(itemStack, "闪电附加")) {
            return;
        }
        // RandomUtils 为apache commons下的一个工具类
        int randomNumber = RandomUtils.nextInt(100);

        // 随机数判断
        if (GemAPI.getItemLightingOdds(itemStack) > randomNumber) {
            LivingEntity livingEntity = (LivingEntity) entity;
            entity.getWorld().strikeLightningEffect(entity.getLocation());
            livingEntity.damage(2);
        }
    }
}
